import { Text, useMessage } from 'alemonjs'
import { selects, validate } from '@src/apps/index'
import { user } from '@src/db/src/models/user/user'

export const regular = /^(!|！|\/)?注册/

const response = onResponse(selects, async e => {
  const [message] = useMessage(e)
  const userId = e.UserId ?? e.UserKey

  // 获取注册指令后的名字
  const match = /^(!|！|\/)?注册\s*(\S+)?/.exec(e.MessageText || '')
  const regName = match && match[2] ? match[2].trim() : ''

  // 检查是否为空
  if (!regName) {
    message.send(format(Text('请输入道号，如：/注册 小柠檬')))
    return
  }

  // 检查用户名是否已存在
  const nameExist = await user.findOneValue({ where: { name: regName } })
  if (nameExist) {
    message.send(format(Text('该道号已存在！')))
    return
  }

  // 检查用户是否已注册
  const exist = await user.findOneValue({ where: { qq_number: userId } })
  if (exist) {
    message.send(format(Text('请勿重复注册！')))
    return
  }

  // 获取当前最大uid
  const lastUser = await user.findOneValue({
    order: [['uid', 'DESC']]
  })
  // Use (lastUser as any).uid if TypeScript does not recognize 'uid' on 'user'
  const lastUserUid = (lastUser as any)?.uid
  const nextUid = lastUserUid ? Number(lastUserUid) + 1 : 10000001

  // 添加新用户
  await user.create({
    qq_number: userId,
    name: regName,
    register_time: new Date(),
    status: 0,
    uid: nextUid
  })

  message.send(format(Text(`[${regName}]注册成功！`)))
})

export default onResponse(selects, [validate, response.current])
